<template>
	<div>
		<div class="search">
			<input 
				type="text" 
				placeholder="请输入中文或拼音" 
				class="input-search" 
				v-model="inputVal" 
				@focus="handleInputFocus" 
				@blur="handleInputBlur"
			>
		</div>
		<div class="search-content" ref="search" v-show="inputVal">
			<ul>
				<li 
					class="search-item border-bottom"
					v-for="item of list" 
					:key="item.id"
					@click="handleCityClick(item.name)"
				>
					{{item.name}}
				</li>
				<li class="search-item border-bottom" v-show="!list.length">没有找到匹配数据</li>
			</ul>
		</div>		
	</div>
</template>

<script>
	import BScroll from 'better-scroll'

	export default {
		name: 'CitySearch',
		props: {
			cities: Object
		},
		data () {
			return {
				inputVal: '',
				list: [],
				timer: null
			}
		},
		watch: {
			// 输入字符与城市列表进行匹配，输出结果
			inputVal () {
				if(this.timer){
					clearTimeout(this.timer)
				}
				this.timer = setTimeout( ()=> {
					const result = []
					for(let i in this.cities){
						this.cities[i].forEach( (item) => {
							if(item.spell.indexOf(this.inputVal) > -1 ||
							 item.name.indexOf(this.inputVal) > -1){
								result.push(item)
							}
						})
					}
					this.list = result
				},100)
			}
		},
		methods: {
			handleCityClick (city) {
				this.$store.dispatch('changeCityAction',city)
				this.$router.push('/')
			},
			handleInputFocus () {
				this.$emit('inputFocus')
			},
			handleInputBlur () {
				this.$emit('inputBlur')
			}			
		},
		// 搜索结果列表滚动
		mounted () {
			this.scroll = new BScroll(this.$refs.search)
		}
	}
</script>

<style lang="stylus" scoped>
	@import "~styles/variable.styl"

	.search
		padding: 0 .1rem
		height:.72rem
		background:$bgColor
		.input-search
			padding:0 1%
			width:98%
			height:.62rem
			line-height:.62rem
			text-align:center
			color:#666
			border-radius:.06rem
	.search-content
		z-index: 1
		overflow: hidden
		position: absolute
		top: 1.58rem
		left: 0
		right: 0
		bottom: 0
		background: #eee
		.search-item
			line-height: .62rem
			padding-left: .2rem
			background: #fff
			color: #666
</style>